import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/styles" as Styles
import "qrc:/qml/components"

Rectangle {
    id: liftTab
    color: "transparent"

    property var liftModel: GlobalResourceViewModel ? GlobalResourceViewModel.liftListModel : null
    property int liftDataRevision: 0
    readonly property int actionColumnWidth: 70 + 70 + 80 + 80 + 3 * Styles.Theme.spacingSmall

    function normalizeFloorList(source) {
        if (!source) {
            return [];
        }
        if (Array.isArray(source)) {
            return source.slice();
        }
        const result = [];
        if (typeof source.length === "number") {
            for (let i = 0; i < source.length; ++i) {
                result.push(source[i]);
            }
            return result;
        }
        if (typeof source.count === "number" && typeof source.get === "function") {
            for (let i = 0; i < source.count; ++i) {
                result.push(source.get(i));
            }
            return result;
        }
        return result;
    }

    function refreshLiftRevision() { liftDataRevision++; }

    Connections {
        target: liftModel
        ignoreUnknownSignals: true
        function onModelReset() { refreshLiftRevision(); }
        function onRowsInserted() { refreshLiftRevision(); }
        function onRowsRemoved() { refreshLiftRevision(); }
        function onDataChanged() { refreshLiftRevision(); }
    }

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingLarge
        spacing: Styles.Theme.spacingLarge

        // 顶部统计卡片
        Row {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingNormal

            KpiCard {
                width: 200
                height: 100
                title: "电梯总数"
                value: GlobalResourceViewModel ? GlobalResourceViewModel.totalLiftCount : 0
                iconSource: "🛗"
                accentColor: Styles.Theme.primary
                enableValueAnimation: false
            }

            KpiCard {
                width: 200
                height: 100
                title: "在线电梯"
                value: {
                    liftDataRevision;
                    if (!liftModel) return 0;
                    let count = 0;
                    for (let i = 0; i < liftModel.rowCount(); i++) {
                        const lift = liftModel.getLiftData(i);
                        if (lift && lift.isOnline) {
                            count++;
                        }
                    }
                    return count;
                }
                iconSource: "✓"
                accentColor: Styles.Theme.success
                enableValueAnimation: false
            }

            KpiCard {
                width: 200
                height: 100
                title: "忙碌电梯"
                value: {
                    liftDataRevision;
                    if (!liftModel) return 0;
                    let count = 0;
                    for (let i = 0; i < liftModel.rowCount(); i++) {
                        const lift = liftModel.getLiftData(i);
                        if (lift && lift.status === "忙碌") {
                            count++;
                        }
                    }
                    return count;
                }
                iconSource: "⚡"
                accentColor: Styles.Theme.warning
                enableValueAnimation: false
            }
        }

        // 电梯列表
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: Styles.Theme.surface
            radius: Styles.Theme.radiusNormal

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingNormal

                // 标题栏
                RowLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingNormal

                    Text {
                        text: "电梯列表"
                        font.pixelSize: Styles.Theme.fontSizeLarge
                        font.weight: Styles.Theme.fontWeightBold
                        color: Styles.Theme.textPrimary
                    }

                    Item { Layout.fillWidth: true }

                    ActionButton {
                        text: "刷新"
                        iconSource: "qrc:/icons/refresh.svg"
                        size: "small"
                        onClicked: {
                            if (GlobalResourceViewModel) {
                                GlobalResourceViewModel.refreshLiftData();
                            }
                        }
                    }
                }

                // 表头
                Rectangle {
                    Layout.fillWidth: true
                    height: 40
                    color: Styles.Theme.surfaceHeader
                    radius: Styles.Theme.radiusSmall

                    RowLayout {
                        anchors.fill: parent
                        anchors.leftMargin: Styles.Theme.spacingNormal
                        anchors.rightMargin: Styles.Theme.spacingNormal
                        spacing: Styles.Theme.spacingNormal

                        Text { Layout.preferredWidth: 80; Layout.alignment: Qt.AlignVCenter; text: "编号"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 100; Layout.alignment: Qt.AlignVCenter; text: "类型"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 100; Layout.alignment: Qt.AlignVCenter; text: "当前楼层"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 100; Layout.alignment: Qt.AlignVCenter; text: "状态"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 100; Layout.alignment: Qt.AlignVCenter; text: "在线状态"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Item { Layout.fillWidth: true }
                        Text {
                            Layout.preferredWidth: actionColumnWidth
                            Layout.alignment: Qt.AlignVCenter
                            text: "操作"
                            font.pixelSize: Styles.Theme.fontSizeNormal
                            font.weight: Styles.Theme.fontWeightMedium
                            color: Styles.Theme.textSecondary
                            horizontalAlignment: Text.AlignHCenter
                        }
                    }
                }

                // 电梯列表
                ListView {
                    id: liftListView
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    spacing: Styles.Theme.spacingSmall
                    boundsBehavior: Flickable.StopAtBounds
                    highlightMoveDuration: 0

                    model: liftModel

                    delegate: Rectangle {
                        id: liftListItem
                        width: liftListView.width
                        height: 60
                        color: index % 2 === 0 ? Styles.Theme.surface : Styles.Theme.backgroundAlternate
                        radius: Styles.Theme.radiusSmall

                        // 平滑的颜色过渡
                        Behavior on color {
                            ColorAnimation { duration: Styles.Theme.animationFast }
                        }

                        RowLayout {
                            anchors.fill: parent
                            anchors.leftMargin: Styles.Theme.spacingNormal
                            anchors.rightMargin: Styles.Theme.spacingNormal
                            spacing: Styles.Theme.spacingNormal

                            // 编号
                            Text {
                                Layout.preferredWidth: 80
                                Layout.alignment: Qt.AlignVCenter
                                text: "电梯 " + model.liftNum
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                font.weight: Styles.Theme.fontWeightMedium
                                color: Styles.Theme.textPrimary
                            }

                            // 类型
                            Text {
                                Layout.preferredWidth: 100
                                Layout.alignment: Qt.AlignVCenter
                                text: model.liftType
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                color: Styles.Theme.textSecondary
                            }

                            // 当前楼层
                            Text {
                                Layout.preferredWidth: 100
                                Layout.alignment: Qt.AlignVCenter
                                text: model.currentFloor + "F"
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                color: Styles.Theme.textPrimary
                            }

                            // 状态
                            StatusIndicator {
                                Layout.preferredWidth: 100
                                Layout.alignment: Qt.AlignVCenter
                                label: model.status
                                animated: false
                                status: {
                                    if (model.status === "空闲") return "success";
                                    if (model.status === "忙碌") return "warning";
                                    if (model.status === "错误") return "error";
                                    return "normal";
                                }
                                showIndicator: true
                                size: "small"
                            }

                            // 在线状态
                            RowLayout {
                                Layout.preferredWidth: 100
                                Layout.alignment: Qt.AlignVCenter
                                spacing: Styles.Theme.spacingXSmall

                                Rectangle {
                                    width: 8
                                    height: 8
                                    radius: 4
                                    Layout.alignment: Qt.AlignVCenter
                                    color: model.isOnline ? Styles.Theme.success : Styles.Theme.danger
                                }

                                Text {
                                    Layout.alignment: Qt.AlignVCenter
                                    text: model.isOnline ? "在线" : "离线"
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                    color: model.isOnline ? Styles.Theme.success : Styles.Theme.danger
                                }
                            }

                            Item {
                                Layout.fillWidth: true
                            }

                            // 操作按钮
                            RowLayout {
                                Layout.preferredWidth: actionColumnWidth
                                Layout.maximumWidth: actionColumnWidth
                                Layout.minimumWidth: actionColumnWidth
                                Layout.alignment: Qt.AlignVCenter
                                spacing: Styles.Theme.spacingSmall

                                ActionButton {
                                    Layout.preferredWidth: 70
                                    text: "开门"
                                    size: "small"
                                    buttonType: "primary"
                                    enabled: model.isOnline && !model.isLocked
                                    onClicked: {
                                        if (GlobalResourceViewModel) {
                                            GlobalResourceViewModel.openLiftDoor(model.liftNum);
                                        }
                                    }
                                }

                                ActionButton {
                                    Layout.preferredWidth: 70
                                    text: "关门"
                                    size: "small"
                                    buttonType: "secondary"
                                    enabled: model.isOnline && !model.isLocked
                                    onClicked: {
                                        if (GlobalResourceViewModel) {
                                            GlobalResourceViewModel.closeLiftDoor(model.liftNum);
                                        }
                                    }
                                }

                                ActionButton {
                                    Layout.preferredWidth: 80
                                    text: model.isLocked ? "解锁" : "锁定"
                                    size: "small"
                                    buttonType: model.isLocked ? "success" : "warning"
                                    onClicked: {
                                        if (GlobalResourceViewModel) {
                                            if (model.isLocked) {
                                                GlobalResourceViewModel.unlockLift(model.liftNum);
                                            } else {
                                                GlobalResourceViewModel.lockLift(model.liftNum);
                                            }
                                        }
                                    }
                                }

                                ActionButton {
                                    Layout.preferredWidth: 80
                                    text: "呼叫"
                                    size: "small"
                                    buttonType: "primary"
                                    enabled: model.isOnline && !model.isLocked
                                    onClicked: {
                                        callLiftDialog.liftNum = model.liftNum;
                                        let floors = normalizeFloorList(model.availableFloors);
                                        if ((!floors || floors.length === 0) && liftModel) {
                                            floors = normalizeFloorList(liftModel.getAvailableFloors(model.liftNum));
                                        }
                                        callLiftDialog.availableFloors = floors;
                                        callLiftDialog.open();
                                    }
                                }
                            }
                        }

                        // 悬停效果
                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            propagateComposedEvents: true
                            onEntered: liftListItem.color = Styles.Theme.surfaceVariant
                            onExited: liftListItem.color = index % 2 === 0 ? Styles.Theme.surface : Styles.Theme.backgroundAlternate
                            onPressed: function(mouse) { mouse.accepted = false; }
                            onClicked: function(mouse) { mouse.accepted = false; }
                        }
                    }

                    ScrollBar.vertical: ScrollBar {
                        policy: ScrollBar.AsNeeded
                    }
                }
            }
        }
    }

    // 呼叫电梯对话框
    CustomDialog {
        id: callLiftDialog
        title: "呼叫电梯"
        dialogWidth: 440
        dialogHeight: Math.min(520, Math.max(380, liftTab.height * 0.8))
        okButtonText: "呼叫"
        cancelButtonText: "取消"
        okButtonEnabled: selectedFloor !== -1 && availableFloors && availableFloors.length > 0

        property int liftNum: 0
        property var availableFloors: []
        property int selectedFloor: -1
        readonly property int listAreaHeight: Math.max(220, Math.min(360, dialogHeight - 140))

        onOpened: selectedFloor = -1
        onAvailableFloorsChanged: {
            if (!availableFloors || availableFloors.indexOf(selectedFloor) === -1) {
                selectedFloor = -1;
            }
        }

        ButtonGroup {
            id: floorSelectionGroup
            exclusive: true
        }

        contentItem: ColumnLayout {
            width: parent ? parent.width : implicitWidth
            spacing: Styles.Theme.spacingNormal

            Text {
                text: "选择目标楼层："
                font.pixelSize: Styles.Theme.fontSizeMedium
                font.weight: Styles.Theme.fontWeightMedium
                color: Styles.Theme.textPrimary
            }

            RowLayout {
                Layout.fillWidth: true
                spacing: Styles.Theme.spacingSmall

                Rectangle {
                    Layout.preferredWidth: 120
                    Layout.preferredHeight: 32
                    radius: Styles.Theme.radiusLarge
                    color: Styles.Theme.surfaceVariant
                    RowLayout {
                        anchors.fill: parent
                        anchors.leftMargin: Styles.Theme.spacingSmall
                        anchors.rightMargin: Styles.Theme.spacingSmall
                        spacing: Styles.Theme.spacingSmall
                        Text {
                            text: "楼层数量"
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }
                        Text {
                            text: callLiftDialog.availableFloors ? callLiftDialog.availableFloors.length : 0
                            font.pixelSize: Styles.Theme.fontSizeNormal
                            font.weight: Styles.Theme.fontWeightMedium
                            color: Styles.Theme.textPrimary
                        }
                    }
                }

                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 32
                    radius: Styles.Theme.radiusLarge
                    color: callLiftDialog.selectedFloor === -1 ? Styles.Theme.surface : Styles.Theme.primary
                    border.width: 1
                    border.color: callLiftDialog.selectedFloor === -1 ? Styles.Theme.border : Styles.Theme.primaryDark

                    Text {
                        anchors.centerIn: parent
                        text: callLiftDialog.selectedFloor === -1 ? "未选择楼层" : "已选择： " + callLiftDialog.selectedFloor + " 楼"
                        color: callLiftDialog.selectedFloor === -1 ? Styles.Theme.textSecondary : Styles.Theme.textOnPrimary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                }
            }

            Text {
                text: "提示：可先选择目标楼层，再点击下方“呼叫”按钮确认操作。"
                color: Styles.Theme.textSecondary
                font.pixelSize: Styles.Theme.fontSizeSmall
                wrapMode: Text.WordWrap
            }

            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: callLiftDialog.listAreaHeight
                radius: Styles.Theme.radiusNormal
                color: Styles.Theme.backgroundSecondary
                border.color: Styles.Theme.border
                border.width: 1

                ListView {
                    id: availableFloorList
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingSmall
                    clip: true
                    spacing: Styles.Theme.spacingSmall
                    model: callLiftDialog.availableFloors

                    delegate: RadioDelegate {
                        id: floorDelegate
                        width: parent ? parent.width : implicitWidth
                        implicitHeight: 48
                        checked: modelData === callLiftDialog.selectedFloor
                        ButtonGroup.group: floorSelectionGroup

                        background: Rectangle {
                            radius: Styles.Theme.radiusSmall
                            border.width: 1
                            border.color: floorDelegate.checked ? Styles.Theme.primary : Styles.Theme.border
                            color: floorDelegate.down || floorDelegate.checked
                                   ? Styles.Theme.backgroundSelected
                                   : Styles.Theme.surface

                            Behavior on color {
                                ColorAnimation { duration: Styles.Theme.animationFast }
                            }
                        }

                        contentItem: RowLayout {
                            anchors.fill: parent
                            anchors.leftMargin: Styles.Theme.spacingNormal
                            anchors.rightMargin: Styles.Theme.spacingNormal
                            spacing: Styles.Theme.spacingSmall

                            Rectangle {
                                Layout.preferredWidth: 30
                                Layout.preferredHeight: 30
                                radius: Styles.Theme.radiusLarge
                                color: floorDelegate.checked ? Styles.Theme.primary : Styles.Theme.surfaceVariant

                                Text {
                                    anchors.centerIn: parent
                                    text: "#"
                                    color: floorDelegate.checked ? Styles.Theme.textOnPrimary : Styles.Theme.textSecondary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }
                            }

                            Text {
                                Layout.fillWidth: true
                                text: modelData + " 楼"
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                font.weight: Styles.Theme.fontWeightMedium
                                color: Styles.Theme.textPrimary
                            }
                        }

                        onClicked: callLiftDialog.selectedFloor = modelData
                    }

                    ScrollBar.vertical: ScrollBar {
                        policy: ScrollBar.AsNeeded
                    }
                }

                Item {
                    anchors.fill: parent
                    visible: !callLiftDialog.availableFloors || callLiftDialog.availableFloors.length === 0

                    Column {
                        anchors.centerIn: parent
                        spacing: Styles.Theme.spacingSmall
                        opacity: 0.8

                        Text {
                            text: "暂无可调度楼层"
                            font.pixelSize: Styles.Theme.fontSizeLarge
                            font.weight: Styles.Theme.fontWeightBold
                            color: Styles.Theme.textSecondary
                            horizontalAlignment: Text.AlignHCenter
                        }

                        Text {
                            text: "请检查电梯配置或稍后再试"
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            color: Styles.Theme.textSecondary
                            horizontalAlignment: Text.AlignHCenter
                        }
                    }
                }
            }
        }

        onAccepted: {
            if (GlobalResourceViewModel && selectedFloor !== -1) {
                GlobalResourceViewModel.callLift(liftNum, selectedFloor);
            }
        }
    }

}
